<template>
	<view class="material-previewer" v-if="show">
		<view class="material-previewer__image" v-if="imageAble" @click="onImageClick">
			<material-image :key="i" :store="store" :width="width" :height="height" />
		</view>
		<view class="material-previewer__video" v-else-if="videoAble">
			<material-video :key="i" :store="store" :width="width" :height="height" />
		</view>
		<view class="material-previewer__office" v-else-if="officeAble">
			<material-office :key="i" :store="store" :width="width" :height="height" @material:office="onOpen" />
		</view>
		<view class="material-previewer__none" v-else>不能预览，但可以点击下载之后在预览</view>
	</view>
</template>

<script>
	import MaterialImage from './preview/image.vue';
	import MaterialVideo from './preview/video.vue';
	import MaterialOffice from './preview/office.vue';
	import MaterialApi from '@/api/user/material';
	import File from './file/file.js';
	export default {
		name: "material-previewer",
		mixins: [File],
		components: {
			MaterialImage,
			MaterialVideo,
			MaterialOffice
		},
		props: {
			index: {
				type: Number,
				default: 0
			},
			material: {
				type: Object,
				default: () => {}
			},
			show: {
				type: Boolean,
				default: true
			},
			width: { // 宽度 (需带单位,支持格式: '100%', '300px', '300rpx')
				type: String,
				default: "70px"
			},
			height: { // 高度 (需带单位,支持格式: '100%', '300px', '300rpx')
				type: String,
				default: "70px"
			},
		},
		data() {
			return {
				store: {},
				i: 1,
			}
		},
		watch: {
			show: function() {
				if (this.show) {
					++this.i;
				}
			},
			material: function() {
				if (this.material && this.material.id) {
					this.load();
				}
			},
		},
		mounted() {
			if (this.material && this.material.id) {
				this.load();
			}
		},
		methods: {
			load: async function() {
				let res = await MaterialApi.preview(this.material.id);
				this.store = res.obj || {};
				this.$emit('material:load', {
					id: this.material.id,
					index: this.index,
					name: this.material.name,
					url: this.store.signedUrl
				});
			},
			onImageClick: function() {
				this.$emit('material:preview', this.index);
			},
			onOpen: function() {
				this.$emit('material:office', true);
			}
		}
	}
</script>
